if (typeof window.onload == "function") {    //判断之前是否有windows.onload
	var saved = null;                        //创建一个保存器
	saved = window.onload;                   //把之前的window.onload赋值
}

window.onload = function() {
	saved();  //第一个onload
	doGetObjects();
	echoPage();
}

var doJson = ''; //将查询的table数据进行一个缓存;方便修改时候直接用,无需再次请求服务器.

var pagesObject = {
	rowCount: 0,
	pageCount: 0,
	pageSize: 0,
	pageCurrent: 0
};
function doGetObjects() {
	//发生请求,响应table界面及数据.
	let current = 1;
	if (pagesObject.pageCurrent != 0) {
		current = pagesObject.pageCurrent
	}
	let size = document.querySelector("#pages>div.page_select_size>select").value;
	let url = '/role/list?current=' + current + '&size=' + size;
	fetch(url)
		.then(res => res.json())
		.then(item => {
			if (item.state === 200) {
				execute(item.data);
			} else {
				alter(item.message);
			}
		})
}

function execute(item) {
	pagesObject.rowCount = item.rowCount;
	pagesObject.pageCount = item.pageCount;
	pagesObject.pageSize = item.pageSize;
	pagesObject.pageCurrent = item.pageCurrent;
	doSetTableBodyRows(item.records);
	doJson = item.records;	 //将table数据保存一份;	
	showPagesInfo();
	aClik();
	selectChange();
}

function doSetTableBodyRows(data) {
	//回显表格数据具体实现
	var tBody = document.getElementById('tablelist');
	tBody.innerHTML = '';  //先清空表再写入数据(清理数据是个好习惯)

	data.forEach(item => {
		var tr = document.createElement('tr');
		var tdId = document.createElement('td');
		var tdName = document.createElement('td');
		var tdInfo = document.createElement('td');
		var tdCz = document.createElement('td');

		tdId.append(item.roleId);
		tdName.append(item.roleName);
		tdInfo.append(strFormat(item.moduleInfo));
		tdCz.innerHTML = ` <input type='button' value='修改' class='btn_modify' onclick='change(${item.roleId})' />
                         <input type='button' value='删除' class='btn_delete' onclick='deleteRole(${item.roleId});' />
						`;

		tr.appendChild(tdId);
		tr.appendChild(tdName);
		tr.appendChild(tdInfo);
		tr.appendChild(tdCz);

		tBody.appendChild(tr);
	})
}

function strFormat(tag) {
	//格式化字符串
	var name = '';
	for (var str of tag) {
		name += ' ' + str.name + ' '
	}
	return name;
}

function queryTag(string) {
	// 封装查找标签;
	return document.querySelector(string);
}

function change(data) {
	//onclick 修改事件(回显全部数据)
	offOn(true);
	let ipt = queryTag('#main form>div>input');
	let span = queryTag('#main form>.roleId');

	let checkGroup = document.getElementsByName('chekedGroup');
	let checked = [];
	doJson.forEach(item => {
		if (item.roleId === data) {
			span.innerText = item.roleId;
			ipt.value = item.roleName;
			checked = item.moduleInfo;
		}
	});
	//双层for循环,不是万不得已不要这么玩,性能大打折扣.
	checkGroup.forEach(group => {
		checked.forEach(check => {
			if (group.value == check.moduleId) {
				group.checked = true;
			}
		});
	})
}

function offOn(out) {
	// add/change的开关;为确保有序的开关组合.
	let main = queryTag('#main>.show_main');
	let achg = queryTag('#main>.add_change');
	if (out) {
		main.style.display = 'none';
		achg.style.display = 'block';
	} else {
		main.style.display = 'block';
		achg.style.display = 'none';
	}
}

function echoPage() {
	// 发生get请求,回显add/change页面(带脏数据的页面)
	var mainBody = queryTag('#main>.add_change');
	let url = '/template/role_modi';
	fetch(url)
		.then(res => res.text())
		.then(result => {
			mainBody.innerHTML = result;
			echoPageFormat();
		})
		.catch(err => {
			console.log(err)
		})
}

function echoPageFormat() {
	// 发生get请求,回显设置权限中的内容.
	let url = '/role/moduleInfo';
	fetch(url)
		.then(res => res.json())
		.then(result => {
			if (result.state === 200) {
				echoPageSetAccess(result.data);
			} else {
				alter(result.message)
			}
		}).catch(err => {
			console.log(err)
		})
}

function echoPageSetAccess(data) {
	//页面清洗并最终格式化界面
	var ipt = queryTag('#main form>div>input');
	ipt.value = '';  //清空角色名称

	var checked = queryTag('#main ul');
	checked.innerHTML = ''; //清空设置权限中的所有标签

	data.forEach(item => {
		var li = document.createElement('li');
		var input = document.createElement('input')

		input.setAttribute('type', 'checkbox');
		input.setAttribute('value', item.moduleId);
		input.setAttribute('name', 'chekedGroup')

		li.appendChild(input);
		li.append(item.name);
		checked.appendChild(li);
	});
}

//删除
function deleteRole(id) {
	let url = '/role/delete/' + id;
	if (!confirm("确定要删除此角色吗？" + id)) return;
	fetch(url, {
		method: 'DELETE'
	}).then(res => res.json())
		.then(res => {
			if (res.state == 200) {
				isShow();
				doGetObjects();
			} else {
				isShow(res.message);
			}
		})
}

//-------------按钮组---------------

function addBtn() {
	//增加按钮
	let ipt = queryTag('#main form>div>input');
	let span = queryTag('#main form>.roleId');
	span.innerText = '';
	let checkGroup = document.getElementsByName('chekedGroup');
	ipt.value = '';
	checkGroup.forEach(item => {
		item.checked = false;
	})
	offOn(true);
}


function exitBtn() {
	//取消按钮
	offOn(false);
}

function saveBtn() {
	//保存按钮	
	let fag = queryTag('#main form>.roleId'); //判断新增或者修改
	if (fag.innerText === '') {
		submit(true);
	} else {
		submit(false);
	}
}

function submit(fag) {
	//fag=true是新增按钮提交/=false是修改提交按钮;
	let addUrl = '/role/add/list';
	let chgUrl = '/role/upadte/list';

	if (fag) {
		fetchPost(addUrl, param());
	} else {
		fetchPost(chgUrl, param());
	}
}

function fetchPost(url, param) {
	//发送请求
	fetch(url, {
		method: 'POST',
		headers: { "Content-Type": "application/json" },
		body: param
	})
		.then(item => item.json())
		.then(result => {
			if (result.state == 200) {
				showTitle(true);
				doGetObjects();
				window.setTimeout(back(false), 3000);
			} else {
				console.log(result.message)
			}
		});
}

function param() {
	//收集参数
	let span = queryTag('#main form>.roleId');
	let input = queryTag('#main form>div>input');
	let checkGroup = document.getElementsByName('chekedGroup');
	let moduleInfo = [];
	let roleName = input.value;
	let roleId = span.innerText;
	checkGroup.forEach(
		item => {
			if (item.checked) {
				moduleInfo.push(item.value);
			}
		});
	return JSON.stringify({ roleId, roleName, moduleInfo });
}

function showTitle(flag) {
	//显示隐藏保存成功后的标题
	let divResult = document.getElementById("save_result_info");
	if (flag)
		divResult.style.display = "block";
	else
		divResult.style.display = "none";
}

function back(tag) {
	showTitle(tag);
	offOn(tag);
}

//-------------执行操作后的提示-------------

function isShow(tag) {
	let info = document.getElementById("operate_result_info");
	info.innerText = ''; //先初始化
	let img = document.createElement('img');
	img.setAttribute('onclick', "this.parentNode.style.display='none';");

	if (tag === undefined) {
		info.className = 'operate_success';
		info.innerText = "删除成功!";

		info.appendChild(img);
		info.style.display = "block";
	} else {
		info.className = 'operate_fail';
		info.innerText = tag;

		info.appendChild(img);
		info.style.display = "block";
	}
}
//------------分页组---------------
function selectChange() {
	let size = document.querySelector("#pages>div.page_select_size>select");
	size.onchange = function() {
		console.log("我被size改了" + size.value)
		pagesObject.pageSize = size.value;
		doGetObjects();
	}
}

function showPagesInfo() {
	let pageText = document.querySelector("#pages>span.page_number");
	pageText.innerText = '当前: 第' + pagesObject.pageCurrent + '页 | 一共: ' + pagesObject.pageCount + '页'
	let pageNum = document.querySelectorAll('#pages a');

	if (pagesObject.pageCurrent == 1) {
		pageNum[pageNum.length - 1].classList.remove('current_page');
		pageNum[0].className = 'current_page';
	}else if (pagesObject.pageCurrent == pagesObject.pageCount) {
		pageNum[pageNum.length - 1].className = 'current_page';
		pageNum[0].classList.remove('current_page');
	} else {
		pageNum.forEach(i => i.classList.remove('current_page'));
	}
}

function aClik() {
	let pageNum = document.querySelectorAll('#pages a');
	for (let i = 0; i < pageNum.length; i++) {
		pageNum[i].onclick = function() {
			switch (i) {
				case 0:
					if (pagesObject.pageCurrent !== 1) {
						pagesObject.pageCurrent = 1;
						doGetObjects();
					}
					break;
				case 1:
					if (pagesObject.pageCurrent !== 1) {
						pagesObject.pageCurrent = --pagesObject.pageCurrent;
						doGetObjects();
					}
					break;
				case 2:
					if (pagesObject.pageCurrent !== pagesObject.pageCount) {
						pagesObject.pageCurrent = ++pagesObject.pageCurrent;
						doGetObjects();
					}
					break;
				case 3:
					if (pagesObject.pageCurrent !== pagesObject.pageCount) {
						pagesObject.pageCurrent = pagesObject.pageCount;
						doGetObjects();
					}
					break;
			}
		}
	}
}

//-------修改和增加时提示-----------
